package org.demo.five;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

/**
 * 
 * @author  
 * @date    2010-10-24
 * @file    org.demo.five.ArraySortedCollection.java
 */
public class ArraySortedCollection<E> implements SortedCollection<E>{
	private Comparator<E> comparator;
	private ArrayList<E> list;
	
	public ArraySortedCollection(Comparator<E> c){
		this.list = new ArrayList<E>();
		this.comparator = c;
	}
	public ArraySortedCollection(Collection<? extends E> src,Comparator<E> c){
		this.list = new ArrayList<E>(src);
		this.comparator = c;
		sortThis();
	}
	
	public Comparator<E> getComparator() {
		return comparator;
	}
	public void setComparator(Comparator<E> comp) {
		this.comparator = comp;
		sortThis();
	}
	
	public boolean add(E e) {
		boolean r = list.add(e);
		sortThis();
		return r;
	}
	public boolean addAll(Collection<? extends E> c) {
		boolean r = list.addAll(c);
		sortThis();
		return r;
	}
	public boolean remove(Object o) {
		boolean r = list.remove(o);
		sortThis();
		return r;
	}
	public boolean removeAll(Collection<?> c) {
		boolean r = list.removeAll(c);
		sortThis();
		return r;
	}
	public boolean retainAll(Collection<?> c) {
		boolean r = list.retainAll(c);
		sortThis();
		return r;
	}
	
	public void clear() {
		list.clear();
	}
	public boolean contains(Object o) {
		return list.contains(o);
	}
	public boolean containsAll(Collection<?> c) {
		return list.containsAll(c);
	}
	public boolean isEmpty() {
		return list.isEmpty();
	}
	public Iterator<E> iterator() {
		return list.iterator();
	}
	public int size() {
		return list.size();
	}
	public Object[] toArray() {
		return list.toArray();
	}
	public <T extends Object> T[] toArray(T[] a) {
		return list.toArray(a);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj) {
		if (obj == this){
			return true;
		}
		if(obj instanceof ArraySortedCollection){
			ArraySortedCollection<E> rhs = (ArraySortedCollection<E>)obj;
			return list.equals(rhs.list);
		}
		return false;
	}
	@Override
	public int hashCode() {
		return list.hashCode();
	}
	@Override
	public String toString() {
		return list.toString();
	}
	
	
	private void sortThis() {
		Collections.sort(list, comparator);
	}
}
